package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.PmsAttr;
import com.atguigu.gulimall.product.entity.PmsAttrGroup;
import com.atguigu.gulimall.product.dao.PmsAttrGroupMapper;
import com.atguigu.gulimall.product.service.IPmsAttrGroupService;
import com.atguigu.gulimall.product.service.IPmsAttrService;
import com.atguigu.gulimall.product.vo.AttrGroupWithAttrsVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 属性分组 服务实现类
 * </p>
 *
 * @author szh
 * @since 2020-12-01
 */
@Service
public class PmsAttrGroupServiceImpl extends ServiceImpl<PmsAttrGroupMapper, PmsAttrGroup> implements IPmsAttrGroupService {

	@Autowired
	private IPmsAttrService attrService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<PmsAttrGroup> page = this.page(
				new Query<PmsAttrGroup>().getPage(params),
				new QueryWrapper<PmsAttrGroup>()
		);

		return new PageUtils(page);
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
		String key = (String) params.get("key");
		//select * from pms_attr_group where catelog_id=? and (attr_group_id=key or attr_group_name like %key%)
		QueryWrapper<PmsAttrGroup> wrapper = new QueryWrapper<PmsAttrGroup>();
		if(!StringUtils.isEmpty(key)){
			wrapper.and((obj)->{
				obj.eq("attr_group_id",key).or().like("attr_group_name",key);
			});
		}

		if( catelogId == 0){
			IPage<PmsAttrGroup> page = this.page(new Query<PmsAttrGroup>().getPage(params),
					wrapper);
			return new PageUtils(page);
		}else {
			wrapper.eq("catelog_id",catelogId);
			IPage<PmsAttrGroup> page = this.page(new Query<PmsAttrGroup>().getPage(params),
					wrapper);
			return new PageUtils(page);
		}

	}

	@Override
	public List<AttrGroupWithAttrsVO> getAttrGroupWithAttrsByCatelogId(Long catelogId) {

		// 1- 查询分组信息
		List<PmsAttrGroup> attrGroupEntityList = this.list(new QueryWrapper<PmsAttrGroup>().eq("catelog_id", catelogId));
		// 2-查询所有属性
		List<AttrGroupWithAttrsVO> collect = attrGroupEntityList.stream().map(group -> {
			AttrGroupWithAttrsVO attrsVO = new AttrGroupWithAttrsVO();
			BeanUtils.copyProperties(group, attrsVO);
			List<PmsAttr> attrs = attrService.getRelationAttr(attrsVO.getAttrGroupId());
			attrsVO.setAttrs(attrs);
			return attrsVO;
		}).collect(Collectors.toList());
		return collect;
	}

}
